//当日账单
var basePage = require('../../../common/BasePage');
var baseList = require('../../../common/BaseList');
Page({
    behaviors: [basePage, baseList],
    data: {
        maxDate: (new Date).getTime() - 24 * 60 * 60 * 1000,
        /**所有总价 */
        total: 0,
        /**产品总价 */
        goodTotal: 0,

        /**当前日期 */
        date: '',
        /**当前日期时间戳 */
        dateTime: 0,
        dateTxt: '',
        showDate: false,
        /**账单图片 */
        photo: "",
        typeArr: [{
                id: 1,
                title: '单日账单'
            }, {
                id: 3,
                title: '物流信息'
            },
            {
                id: 2,
                title: '欠款明细'
            },
        ],
        tabIndex: 2,
        billArr: [],
        expressArr: [],
        /**总打包费 */
        express_pack_amount: 0,
        /**总寄费 */
        express_freight: 0,
        /**总送货费 */
        express_short_freight: 0,
        reqUrl: '/home/user/debt',
        areaArr: [],
        gridIndex: 0,
        wh_id: 1,
        showWuliu: false,
        wuliuList: [],
        wuliuactive: 0,
        showPay:false,//支付方式
        // pay:"allin",
        // payType:1,
        orderInfo:{}
    },
    // let pack_amount=express.pack_amount*express.nums;
    // let short_freight=express.short_freight*express.nums;
    // let freight=express.freight*express.nums;
    onLoad: function (options) {
        this.getArea()
        // if (!this.data.areaData || !this.data.areaData.length) {
        //     let areaData = getApp().globalData.areaData;
        //     let areaArr = [];
        //     for (let i = 1; i < areaData.length; i++) {
        //         areaArr.push(areaData[i]);
        //     }
        //     this.setData({
        //         areaData,
        //         areaArr,
        //         wh_id: areaData[0].wh_id
        //     })
        //     this.getPayType(areaData[0].wh_id)
        // }
        if (options.photo) {
            return this.setData({
                photo: this.get_thumb(options.photo, "wide")
            })
        }
        if (options.tabIndex == 1) { //订单跳转查询物流
            this.setData({
                wh_id: options.wh_id,
                tabIndex: options.tabIndex,
                date: new Date(options.day)
            })
        }
        this.req_data();
        

    },
    //获取仓库
    getArea(){
        this.request({
            url:this.data.host+"/home/getWarehouse?from=1"
        },res=>{
            let areaData = res.data;
            let areaArr = [];
            for (let i = 1; i < areaData.length; i++) {
                areaArr.push(areaData[i]);
            }
            var wh_id=1
            if(areaData.length>0){
                wh_id=areaData[0].wh_id
                this.getPayType(areaData[0].wh_id) 
            }
            this.setData({
                areaData,
                areaArr,
                wh_id: wh_id
            })
            console.log("areaData",this.data.areaData)
        })
    },
    area_change(e) {
        let index = e.currentTarget.dataset.index;
        // let detail = e.detail;
        // getApp().globalData.warehouse = this.data.areaData[index];
        // console.log("whid",this.data.areaData[index])
        // this.data.tabIndex = index;
        
        this.setData({
            gridIndex: index,
            wh_id: this.data.areaData[index].wh_id
        })
        this.req_data();
        this.getPayType(this.data.wh_id)

    },
    type_change(e) {
        console.log("type_change", e);
        var date = ""
        if (e.currentTarget.dataset.index != 2) {
            date = new Date(e.currentTarget.dataset.item.day_label)
        }

        this.setData({
            tabIndex: e.currentTarget.dataset.index,
            date: date
        })
        // this.data.tabIndex = e.detail.index;
        this.req_data();

    },

    /**小于10加0返回，如01,09*/
    init_day(num) {
        if (num < 10) {
            return "0" + num.toString();
        }
        return num.toString();
    },
    date_confirm(e) {
        console.log("cls:选中日期", e);
        this.data.date = new Date(e.detail);
        this.req_data();
        this.setData({
            showDate: false,
        })
    },
    req_data() {
        if (this.data.tabIndex == 0 || this.data.tabIndex == 1) { //获取每日账单
            if (!this.data.date) {
                this.data.date = new Date(this.data.maxDate);
            }
            var date = this.data.date;
            console.log("date", date);
            this.setData({
                dateTime: this.data.date.getTime(),
                dateTxt: date.getFullYear() + "年" + (date.getMonth() * 1 + 1).toString() + "月" + date.getDate() + "日"
            })
            let day = date.getFullYear() + this.init_day(date.getMonth() * 1 + 1) + this.init_day(date.getDate());
            this.request({
                url: this.data.host + '/home/user/newBill',
                data: {
                    day: day,
                    wh_id: this.data.wh_id
                },
                loadingTip: '正在加载数据'
            }, res => {
                console.log("当日账单", res);
                let total = 0;

                let express_pack_amount = 0;
                let express_freight = 0;
                let express_short_freight = 0;
                res.data.map(val => {
                    val.total = (val.nums * val.product_price).toFixed(2);
                })
                //物流统计
                let expressArr = [];
                total = res.express_total_price + res.total_price;
                res.express.map(val => {
                    // console.log("val",val)
                    val.express_detail.map(express => {
                        // console.log("express",express)
                        let name = val.express_type_label + "(" + express.weight + "kg)";
                        if (val.express_type == 0) {
                            name = val.express_type_label + "(" + express.box_type_label + ")"
                        }
                        let pack_amount_total = express.pack_amount * express.nums;
                        // let short_freight=express.short_freight*express.nums;
                        let freight_total = express.freight * express.weight + express.short_freight * express.nums;
                        express_pack_amount += pack_amount_total;
                        express_freight += freight_total;
                        // express_short_freight+=short_freight;
                        expressArr.push({
                            name,
                            total_freight: express.total_freight,
                            pack_amount_total: pack_amount_total.toFixed(2),
                            freight_total: freight_total.toFixed(2),
                            nums: express.nums,
                            freight: express.freight,
                            pack_amount: express.pack_amount,
                            short_freight: express.short_freight,
                            company_name: val.company_name,
                            company_staff_mobile: val.company_staff_mobile,
                            company_staff_name: val.company_staff_name,
                            delivery_name: val.delivery_name,
                            delivery_mobile: val.delivery_mobile,
                            sender_name: val.sender_name,
                            sender_mobile: val.sender_mobile,
                            kd_data: val.kd_data,
                            shipping_code: val.shipping_code,
                            have_shipping: val.have_shipping

                        })
                    })
                })
                this.setData({
                    total: total.toFixed(2),
                    express_short_freight: express_short_freight.toFixed(2),
                    goodTotal: res.total_price,
                    billArr: res.data,
                    expressArr: expressArr,

                    express_total_amount: res.express_total_amount,
                    express_total_price: res.express_total_price,
                    express_freight: res.express_total_freight,
                    express_pack_amount: res.express_total_pack,

                })
            });
            return;
        }
        this.data.current_page = 0;
        var param = {
            wh_id: this.data.wh_id
        }
        this.setData({
            reqData: param
        })
        this.req_items();
        // this.request({
        //     url: this.data.host + '/home/user/bill?type=' + this.data.typeArr[this.data.tabIndex].id,
        //     loadingTip: '正在加载数据'
        // }, res => {
        //     console.log("当日账单", res);
        //     if (res.data.length > 0) {
        //         this.setData({
        //             photo: this.get_thumb(res.data[0].photo, "wide")
        //         })
        //     } else {
        //         this.setData({
        //             photo: ''
        //         })
        //         wx.showToast({
        //             title: '暂无账单数据',
        //             icon: 'none'
        //         })
        //     }
        // });
    },
    onPayType(e){
        this.setData({
            orderInfo:e.currentTarget.dataset,
            showPay:true
        })
    },
    pay_click(e) {
        // return console.log(e);
        let that = this;
        // let i=e.currentTarget.dataset.index;
        // that.setData({
        //     [`itemArr[${i}].refund_amount`]:-1
        // })
        // var data = e.currentTarget.dataset
        var data = this.data.orderInfo
        data.code = this.data.pay
        this.setData({
            showPay: false
        })
        this.request({
            url: this.data.host + '/home/payment/debt',
            loadingTip: '调起支付...',
            data: data,
            method: 'post'
        }, res => {
            console.log(res);
            if (this.data.pay == "allin") {
                //通联支付
                var payInfo = res.data.payInfo
                if (payInfo) {
                    payInfo = JSON.parse(payInfo)
                    wx.requestPayment({
                        ...payInfo,
                        success(res) {
                            // console.log('pay success', res);
                            wx.showToast({
                                title: '支付成功',
                            })
                            let i = e.currentTarget.dataset.index;
                            that.setData({
                                [`itemArr[${i}].refund_amount`]: 0
                            })
                        },
                        fail(err) {
                            wx.showToast({
                                title: '支付失败',
                            })
                            // console.error('pay fail', err)
                        },
    
                    })
                }else if(res.data.extraData){//跳转收银台小程序
                    var extraData=res.data.extraData
                    console.log("extraData",extraData)
                    // wx.openEmbeddedMiniProgram
                    
                    wx.navigateToMiniProgram({
                        appId: 'wxef277996acc166c3',
                        extraData: {
                            ...extraData
                        },
                        success() {
                            console.log('成功打开通联小程序');
                            // wx.showToast({
                            //     title: '支付成功',
                            // })
                            let i = e.currentTarget.dataset.index;
                            that.setData({
                                [`itemArr[${i}].refund_amount`]: 0
                            })
                        }
                    })
                    // this.alinePay(extraData,this.pay_ok(e.currentTarget.dataset.index))

                }else{
                    wx.showToast({
                      title: '支付失败',
                      icon:"none"
                    })
                }
               
            }else if (this.data.pay == "wxpay"){
                wx.requestPayment({
                    ...res.data.pay_data,
                    success(res) {
                        wx.showToast({
                            title: '支付成功',
                        })
                        let i = e.currentTarget.dataset.index;
                        that.setData({
                            [`itemArr[${i}].refund_amount`]: 0
                        })

                    },
                    fail(err) {
                        wx.showToast({
                            title: '支付失败',
                            icon: 'none'
                        })
                    }
                })
            }else{
                wx.showToast({
                    title: '支付成功',
                })
                let i = e.currentTarget.dataset.index;
                that.setData({
                    [`itemArr[${i}].refund_amount`]: 0
                })
            }

        })
    },
    pay_ok(i){
        wx.showToast({
            title: '支付成功',
        })
        this.setData({
            [`itemArr[${i}].refund_amount`]: 0
        })
    },
    onWuliu(e) {
        var express = e.currentTarget.dataset.express
        console.log("express", express)
        var kd_data = express.kd_data
        var list = []
        kd_data.map(val => {
            list.push({
                text: val.context,
                desc: val.time
            })
        })
        this.setData({
            wuliuList: list,
            showWuliu: true
        })
    },
    onClose() {
        this.setData({
            showWuliu: false
        })
    },
    onClose2(){
        this.setData({
            showPay:false
        })
    },
    onClick(event) {
        let name = event.currentTarget.dataset.name;
        // this.data.payData.code = name;
        this.setData({
            pay: name,
        })
    },
})